package com.ceair.flight.refund.service.impl;

import com.alibaba.fastjson.JSON;
import com.ceair.flight.refund.dto.nonflight.SeatRes;
import com.ceair.flight.refund.service.IRefundOtherProductService;
import com.ceair.flight.refund.service.IRefundSupportService;
import com.ceair.flight.refund.util.Constant;
import com.ceair.flight.refund.util.Constants;
import com.ceair.muservice.baggage.dto.EmdBageOrderListDto;
import com.ceair.muservice.baggage.dto.QueryAvailSegsReq;
import com.ceair.muservice.baggage.dto.RefundBageReq;
import com.ceair.muservice.baggage.dto.RefundBageRes;
import com.ceair.muservice.baggage.feign.client.IFndBaggage;
import com.ceair.muservice.basicdata.dto.channel.ChannelManageDto;
import com.ceair.muservice.checkin.dto.CheckInFamilyReq;
import com.ceair.muservice.checkin.dto.CheckInFamilyRes;
import com.ceair.muservice.checkin.dto.PwInputReq;
import com.ceair.muservice.checkin.dto.PwRes;
import com.ceair.muservice.checkin.feign.IFnCheckin;
import com.ceair.muservice.emd.dto.EMDOrderDto;
import com.ceair.muservice.emd.dto.EMDRefundTktReq;
import com.ceair.muservice.emd.dto.EMDRefundTktRes;
import com.ceair.muservice.emd.dto.EmdOrderListReq;
import com.ceair.muservice.emd.dto.EmdOrderListRes;
import com.ceair.muservice.emd.dto.EmdSeatOrderListDto;
import com.ceair.muservice.emd.dto.EmdSeatOrderReq;
import com.ceair.muservice.emd.dto.EmdSeatOrderRes;
import com.ceair.muservice.emd.feign.client.IFnEmd;
import com.ceair.muservice.wifi.dto.ManageQueryReq;
import com.ceair.muservice.wifi.dto.WifiCancelReqDto;
import com.ceair.muservice.wifi.dto.WifiCancelResDto;
import com.ceair.muservice.wifi.dto.WifiOrderDto;
import com.ceair.muservice.wifi.feign.IWifiCancel;
import com.google.gson.Gson;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 改期非航产品处理
 */
@Service
public class RefundOtherProductServiceImpl implements IRefundOtherProductService {

    private static final Logger logger = Logger.getLogger(RefundOtherProductServiceImpl.class);

    @Autowired
    IRefundSupportService supportService;

    @Autowired
    IWifiCancel wifiService;

    @Autowired
    IFnEmd emdService;

    @Autowired
    IFndBaggage baggageService;

    @Autowired
    IFnCheckin checkinService;

    /**
     * 退订非航产品 （wifi、emd、baggage）
     *
     * @param orderNo
     * @param ticketNo
     * @param firstName
     * @param midName
     * @param lastName
     * @param saleChannel
     * @param segId
     */
    @Override
    public void doRefundOtherProducts(String orderNo, String ticketNo, String firstName, String midName, String lastName,
                                      String saleChannel, String segId) {
        try {
            logger.info("退订非航产品开始, 大订单号：" + orderNo + " 航段ID：" + segId);
            // 查询wifi
            List<WifiOrderDto> wifiOrderList = queryWifiByOrder(ticketNo, firstName, midName, lastName);
            for (WifiOrderDto wifiOrderDto : wifiOrderList) {
                // 退订wifi
                refundWifi(wifiOrderDto);
            }

            // 查询emd
            List<EMDOrderDto> emdOrderList = queryEmdOrder(ticketNo, firstName, midName, lastName);
            for (EMDOrderDto emdOrderDto : emdOrderList) {
                // 退订emd
                refundEmdOrder(emdOrderDto.getEmdOrderNo());
            }

            // 查询行李
            List<EmdBageOrderListDto> baggageOrderList = getEmdBageOrderList(orderNo, ticketNo, firstName, midName,
                    lastName, saleChannel);
            String site = Constant.EMPTY;
            ChannelManageDto channelDto = supportService.findChannelInfoByChannel(saleChannel);
            if (channelDto != null) {
                site = channelDto.getLanguageCode();
            }
            for (EmdBageOrderListDto emdBageOrderListDto : baggageOrderList) {
                // 退订行李
                refundBaggage(emdBageOrderListDto, saleChannel, site);
            }
            logger.info("退订非航产品结束");
        } catch (Exception e) {
            logger.info("退订非航产品异常, msg：" + e.getMessage());
        }
    }

    /**
     * 查询WIFI
     *
     * @param ticketNo
     * @param firstName
     * @param midName
     * @param lastName
     * @return
     */
    @Override
    public List<WifiOrderDto> queryWifiByOrder(String ticketNo, String firstName, String midName, String lastName) {
        List<WifiOrderDto> wifiOrderList = new ArrayList<>();
        try {
            ManageQueryReq req = new ManageQueryReq();
            req.setTktNo(ticketNo);
            req.setFirstName(firstName);
            req.setMiddleName(midName);
            req.setLastName(lastName);
            logger.info("查询wifi订单开始, 入参：" + new Gson().toJson(req));
            wifiOrderList = wifiService.queryWifiOederByTicket(req);
            if (CollectionUtils.isEmpty(wifiOrderList)) {
                logger.info("没有查询到wifi订单");
                return wifiOrderList;
            }
            logger.info("查询wifi订单结束，出参：" + new Gson().toJson(wifiOrderList));
        } catch (Exception e) {
            logger.error("查询wifi订单异常， msg：" + e.getMessage());
        }
        return wifiOrderList;
    }

    /**
     * 取消wifi
     *
     * @param wifiOrderDto
     * @return
     */
    @Override
    public void refundWifi(WifiOrderDto wifiOrderDto) {
        try {
            WifiCancelReqDto reqDto = new WifiCancelReqDto();
            reqDto.setWifiOrderNo(wifiOrderDto.getWifiOrderNo());
            reqDto.setAlphaOrderNo(wifiOrderDto.getJobOrderNo());
            logger.info("退订wifi开始，入参：" + new Gson().toJson(wifiOrderDto) + "接口入参：" + new Gson().toJson(reqDto));
            WifiCancelResDto resDto = wifiService.cancelWifi(reqDto);
            if (resDto != null) {
                if (Constant.WIFI_RETURN_CODE.equals(resDto.getResultCode())) {
                    logger.info("退订wifi成功, 出参：" + new Gson().toJson(resDto));
                } else {
                    logger.error("退订wifi失败，msg：" + resDto.getResultMsg());
                }
            } else {
                logger.error("退订wifi失败");
            }
        } catch (Exception e) {
            logger.error("调用退订wifi接口异常，msg：" + e.getMessage());
        }
    }

    /**
     * EMD订单列表查询
     *
     * @param ticketNo
     * @param firstName
     * @param midName
     * @param lastName
     * @return
     */
    @Override
    public List<EMDOrderDto> queryEmdOrder(String ticketNo, String firstName, String midName, String lastName) {
        List<EMDOrderDto> emdOrderList = new ArrayList<>();
        try {
            EmdOrderListReq req = new EmdOrderListReq();
            req.setAirTicketNo(ticketNo);
            req.setFirstName(firstName);
            req.setMiddleName(midName);
            req.setLastName(lastName);
            logger.info("查询EMD开始, 入参：" + new Gson().toJson(req));
            EmdOrderListRes emdOrderListRes = emdService.searchEmdOrderListByTicketInfo(req);
            emdOrderList = emdOrderListRes.getEmdOrderDtoList();
            if (!("EMDSEAT0000".equals(emdOrderListRes.getResultCode())) || CollectionUtils.isEmpty(emdOrderList)) {
                logger.info("没有查询到EMD订单");
                return emdOrderList;
            }
            logger.info("查询EMD结束，出参：" + new Gson().toJson(emdOrderList));
        } catch (Exception e) {
            logger.error("查询EMD接口异常， msg：" + e.getMessage());
        }
        return emdOrderList;
    }

    /**
     * EMD退票
     *
     * @param emdOrderNo
     */
    @Override
    public EMDRefundTktRes refundEmdOrder(String emdOrderNo) {
        EMDRefundTktRes res = null;
        try {
            logger.info("退订EMD开始，EMD订单号：" + emdOrderNo);
            EMDRefundTktReq req = new EMDRefundTktReq();
            req.setEmdOrderNo(emdOrderNo);
            res = emdService.refundSeat(req);
            if (res != null) {
                if (Constant.EMD_RETURN_CODE.equals(res.getResultCode())) {
                    logger.info("退订EMD成功，出参：" + new Gson().toJson(res));
                } else {
                    logger.error("退订EMD失败，msg：" + res.getResultMsg());
                }
            } else {
                logger.error("退订EMD失败");
            }
        } catch (Exception e) {
            logger.error("调用退订EMD接口异常，msg：" + e.getMessage());
        }
        return res;
    }

    /**
     * 行李查询
     *
     * @param orderNo
     * @param ticketNo
     * @param firstName
     * @param midName
     * @param lastName
     * @param saleChannel
     * @return
     */
    @Override
    public List<EmdBageOrderListDto> getEmdBageOrderList(String orderNo, String ticketNo, String firstName,
                                                         String midName, String lastName, String saleChannel) {
        List<EmdBageOrderListDto> baggageOrderList = new ArrayList<>();
        try {
            QueryAvailSegsReq queryReq = new QueryAvailSegsReq();
            queryReq.setSalesChannel(saleChannel);
            queryReq.setTicketNo(ticketNo);
            queryReq.setPassengerFirstName(firstName);
            queryReq.setPassengerMiddleName(midName);
            queryReq.setPassengerLastName(lastName);
            logger.info("查询行李开始， 入参：" + new Gson().toJson(queryReq));
            baggageOrderList = baggageService.queryBaggageByTicket(queryReq);
            if (CollectionUtils.isEmpty(baggageOrderList)) {
                logger.info("没有行李订单");
                return baggageOrderList;
            }
            logger.info("查询行李结束， 出参：" + new Gson().toJson(baggageOrderList));
        } catch (Exception e) {
            logger.info("查询行李异常，msg:  " + e.getMessage());
        }
        return baggageOrderList;
    }

    /**
     * 退订行李
     *
     * @param baggageDto
     * @param saleChannel
     * @param site
     * @return
     */
    @Override
    public void refundBaggage(EmdBageOrderListDto baggageDto, String saleChannel, String site) {
        try {
            RefundBageReq req = new RefundBageReq();
            req.setSalesChannel(saleChannel);
            req.setBaggageOrderNo(baggageDto.getBageOrderNo());
            req.setSite(site);
            req.setUserId(baggageDto.getSessionUserId());
            logger.info("退订行李开始，入参：" + new Gson().toJson(req));
            RefundBageRes refundBageRes = baggageService.refundBaggage(req);
            if (refundBageRes != null) {
                if (Constant.RETURN_CODE.equals(refundBageRes.getResultCode())) {
                    logger.info("退订行李成功, 出参：" + new Gson().toJson(refundBageRes));
                } else {
                    logger.error("退订行李失败，msg：" + refundBageRes.getResultMsg());
                }
            } else {
                logger.info("退订行李失败");
            }
            logger.info("退订行李结束，出参：" + new Gson().toJson(refundBageRes));
        } catch (Exception e) {
            logger.info("退订行李异常，msg：" + e.getMessage());
        }
    }

    /**
     * 已值机票获取是否本渠道和座位信息
     *
     * @param tktNo 已值机票号
     * @return 如果是本渠道， 返回的dto里标记为true 和 座位号;
     * 如果不是本渠道，返回的dto里标记为false，座位号为null
     */
    @Override
    public SeatRes getLocalChannelSeat(String tktNo) {
        Assert.notNull(tktNo, "已值机票号不能为空！");
        logger.info("开始查询已值机票渠道和座位信息入参:\t" + tktNo);

        EmdSeatOrderReq req = new EmdSeatOrderReq();
        req.setFlightTktNo(tktNo);
        /**
         * 3 已出票
         */
        req.setOrderSt(Arrays.asList("3"));

        logger.info("查询EMD订单入参:\n" + JSON.toJSONString(req));
        EmdSeatOrderRes emdSeatOrderRes = emdService.searchSeatOrder(req);
        logger.info("EMD订单接口出参:\n" + JSON.toJSON(emdSeatOrderRes));

        SeatRes res = new SeatRes();
        if (!"EMDSEAT0000".equals(emdSeatOrderRes.getResultCode())) {
            res.setResultCode(Constants.ERROR_CODE);
            res.setResultMsg("查询EMD订单失败！");
        } else {
            res.setResultCode(Constants.SUCCESS_CODE);
            res.setResultMsg(Constants.SUCCESS_MSG);
            /**
             * 查询出EMD订单为空，则非本渠道
             */
            List<EmdSeatOrderListDto> emdSeatOrderListDtos = emdSeatOrderRes.getEmdList();
            if (CollectionUtils.isEmpty(emdSeatOrderListDtos)) {
                res.setLcFlag(false);
            } else {
                res.setLcFlag(true);
                res.setSeatNo(emdSeatOrderListDtos.get(0).getSeatxyz());
            }
        }
        logger.info("已值机票获取是否本渠道和座位信息出参:\n" + JSON.toJSONString(res));
        return res;
    }

    /**
     * 多人值机
     *
     * @param req
     * @return
     */
    @Override
    public CheckInFamilyRes checkInFamily(CheckInFamilyReq req) {
        Assert.notNull(req, "调用多人值机接口入参为空！");
        logger.info("调用多人值机接口入参:\n" + JSON.toJSONString(req));
        CheckInFamilyRes res = checkinService.checkInFamily(req);
        logger.info("调用多人值机接口出参:\n" + JSON.toJSON(res));
        return res;
    }

    /**
     * 取消值机
     *
     * @param req
     * @return
     */
    @Override
    public PwRes doDelPsr(PwInputReq req) {
        Assert.notNull(req, "调用取消值机接口入参为空！");
        logger.info("调用取消值机接口入参:\n" + JSON.toJSONString(req));
        PwRes res = checkinService.doDelPsr(req);
        logger.info("调用取消值机接口出参:\n" + JSON.toJSON(res));
        return res;
    }
}
